package com.ztesoft.web.baseconfig.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ztesoft.core.common.Page;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.JsonUtil;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.dao.DmPlanRelationDao;
import com.ztesoft.web.baseconfig.db.po.DmPlanPO;
import com.ztesoft.web.baseconfig.db.po.DmPlanRelationPO;
import com.ztesoft.web.baseconfig.db.po.DmSrcTablePO;
import com.ztesoft.web.baseconfig.db.po.DmStrategyPO;
import com.ztesoft.web.baseconfig.db.po.DmTargetTablePO;
import com.ztesoft.web.baseconfig.db.po.StrategyNodePO;
import com.ztesoft.web.baseconfig.db.po.SubTablePO;
import com.ztesoft.web.baseconfig.db.po.TableNamePO;
import com.ztesoft.web.baseconfig.db.po.TargetTablePO;
import com.ztesoft.web.baseconfig.service.IDmPlanService;
import com.ztesoft.web.baseconfig.service.IDmSrcTableService;
import com.ztesoft.web.baseconfig.service.IDmStrategyService;
import com.ztesoft.web.baseconfig.service.IDmTargetTableService;
import com.ztesoft.web.baseconfig.service.ISubTableDefineService;
import com.ztesoft.web.common.DMSConstant.Status;

/**
 * <Description>策略管理 <br>
 * 
 * @author lin.jie <br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2015年8月4日 <br>
 * @since V1.0<br>
 * @see com.ztesoft.web.baseconfig.controller <br>
 */

@Controller
@RequestMapping("/baseconfig/dmstrategy")
public class DmStrategyController {

	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(DmStrategyController.class);

	@Autowired
	private IDmStrategyService dmStrategyService;
	@Autowired
	private IDmPlanService dmPlanService;
	@Autowired
	private IDmSrcTableService dmSrcTableService;
	@Autowired
	private IDmTargetTableService dmTargetTableService;
	@Autowired
	private ISubTableDefineService subTableDefineService;

	@Autowired
	private DmPlanRelationDao dmPlanRelationDao;

	@RequestMapping("index")
	public String index(Model model) {
		return "baseconfig/jsp/dmStrategy";
	}

	@RequestMapping("queryRecordByPage")
	@ResponseBody
	public Page<DmStrategyPO> queryRecordByPage(DmStrategyPO record, Page<DmStrategyPO> resultPage)
			throws BaseAppException {
		resultPage = dmStrategyService.selectByArgAndPage(record, resultPage);
		return resultPage;
	}

	@RequestMapping("queryRecordList")
	@ResponseBody
	public StrategyNodePO[] queryRecordList(DmStrategyPO record, HttpServletRequest request) throws BaseAppException {
		record.setDmPlanId(Integer.valueOf(request.getParameter("dmPlanId")));
		return dmStrategyService.selectAllForTree(record);
	}

	/**
	 * 新增提交，保证策略名称不同
	 * 
	 * @param record
	 * @return 0:状态为00X，返回报错;1:存在相同名称的策略，不可以新增;
	 * @throws BaseAppException
	 */
	@RequestMapping("add")
	@ResponseBody
	public DmStrategyPO add(DmStrategyPO record) throws BaseAppException {
		logger.debug("add record begin...record=[{0}]", record);
		dmStrategyService.add(record);
		return record;
	}

	@RequestMapping("update")
	@ResponseBody
	public DmStrategyPO update(DmStrategyPO record) throws BaseAppException {
		logger.debug("modify record begin...record=[{0}]", record);
		dmStrategyService.update(record);
		return record;
	}

	@RequestMapping("delete")
	@ResponseBody
	public int delete(DmStrategyPO record) throws BaseAppException {
		logger.debug("delete record begin...record=[{0}]", record);
		return dmStrategyService.delete(record);
	}

	@RequestMapping("qryRecordInfo")
	@ResponseBody
	public DmStrategyPO qryRecordInfo(@RequestParam(value = "dmStrategyId", required = true) Integer dmStrategyId)
			throws BaseAppException {
		DmStrategyPO record = dmStrategyService.selectByPrimaryKey(dmStrategyId);
		return record;
	}

	/**
	 * 保存一个策略下的所有信息，包括：计划策略关系、策略、策略数据关系、源数据、目标数据
	 * 
	 * @param record
	 * @return 1：保存成功，没问题；2：保存失败，有问题
	 * @throws BaseAppException
	 */
	@RequestMapping("addAllInfoOfOneStrategy")
	@ResponseBody
	public int addAllInfoOfOneStrategy(DmTargetTablePO dttPO, DmSrcTablePO dstPO) throws BaseAppException, Exception {
		logger.debug("保存整条计划数据，目标数据=[{0}]，源表数据=[{1}]", dttPO, dstPO);
		// 把计划下的所有0DA状态的策略改为00A
		DmPlanPO dpPO = dmPlanService.updateDToA(dstPO.getDmPlanId());
		// 源表
		dstPO.setTableNameArray(JsonUtil.toArray(dstPO.getTableName(), TableNamePO.class));
		if (!"[null]".equals(dstPO.getSubTablesStr())) {
			dstPO.setSubTables(JsonUtil.toList(dstPO.getSubTablesStr(), SubTablePO.class));
		}
		List<SubTablePO> subTablePOList = dstPO.getSubTables();
		if (Utils.notEmpty(subTablePOList)) {
			for (int i = 0; i < subTablePOList.size(); i++) {
				if (Utils.isEmpty(subTablePOList.get(i))) {
					subTablePOList.remove(i);
					i--;
					continue;
				}
				subTablePOList.get(i).setSubTableNames(
						JsonUtil.toArray(subTablePOList.get(i).getSubTableName(), TableNamePO.class));
			}
		}
		dmStrategyService.addSomeInfoOfOneStrategy(dstPO, Status.SUCCESS.toString());
		if (dpPO.getOperType() == 0) {// 需要备份
			// 目标表
			dttPO.setTargetTables(JsonUtil.toList(dttPO.getTargetTableStr(), TargetTablePO.class));
			dttPO.setTargetColMapList(JsonUtil.toList(dttPO.getTargetColMaps(), Object.class));
			List<TargetTablePO> targetTablePOList = dttPO.getTargetTables();
			for (int i = 0; i < targetTablePOList.size(); i++) {
				if ("".equals(targetTablePOList.get(i).getSrcTableName())) {
					targetTablePOList.remove(i);
					break;
				}
				targetTablePOList.get(i).setTargetTableNamePO(
						JsonUtil.toArray(targetTablePOList.get(i).getTargetTableName(), TableNamePO.class));
			}
			dmTargetTableService.addWithOther(dttPO, Status.SUCCESS.toString());
		}
		return 1;
	}

	/**
	 * 保存一个策略下的所有信息，包括：计划策略关系、策略、策略数据关系、源数据、目标数据
	 * 
	 * @param record
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("addForDraftWithOKAtFourthStep")
	@ResponseBody
	public int addForDraftWithOKAtFourthStep(DmTargetTablePO dttPO, DmSrcTablePO dstPO) throws BaseAppException,
			Exception {
		// 源表
		dstPO.setTableNameArray(JsonUtil.toArray(dstPO.getTableName(), TableNamePO.class));
		if (!"[null]".equals(dstPO.getSubTablesStr())) {
			dstPO.setSubTables(JsonUtil.toList(dstPO.getSubTablesStr(), SubTablePO.class));
		}
		List<SubTablePO> subTablePOList = dstPO.getSubTables();
		if (Utils.notEmpty(subTablePOList)) {
			for (int i = 0; i < subTablePOList.size(); i++) {
				if (Utils.isEmpty(subTablePOList.get(i))) {
					subTablePOList.remove(i);
					i--;
					continue;
				}
				subTablePOList.get(i).setSubTableNames(
						JsonUtil.toArray(subTablePOList.get(i).getSubTableName(), TableNamePO.class));
			}
		}

		dmStrategyService.addSomeInfoOfOneStrategy(dstPO, Status.DRAFT.toString());
		// 目标表
		dttPO.setTargetTables(JsonUtil.toList(dttPO.getTargetTableStr(), TargetTablePO.class));
		dttPO.setTargetColMapList(JsonUtil.toList(dttPO.getTargetColMaps(), Object.class));
		List<TargetTablePO> targetTablePOList = dttPO.getTargetTables();
		for (int i = 0; i < targetTablePOList.size(); i++) {
			if ("".equals(targetTablePOList.get(i).getSrcTableName())) {
				targetTablePOList.remove(i);
				break;
			}
			targetTablePOList.get(i).setTargetTableNamePO(
					JsonUtil.toArray(targetTablePOList.get(i).getTargetTableName(), TableNamePO.class));
		}
		dmTargetTableService.addWithOther(dttPO, Status.DRAFT.toString());
		return 1;
	}

	/**
	 * 获取有关策略的所有信息，包括源数据、目标数据等
	 * 
	 * @param dmStrategyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getStrategyAllInfo")
	@ResponseBody
	public DmStrategyPO getStrategyAllInfo(@RequestParam(value = "dmStrategyId", required = true) Integer dmStrategyId)
			throws Exception {
		DmStrategyPO dsPO = dmStrategyService.selectByPrimaryKey(dmStrategyId);
		dsPO.setDmSrcTablePO(dmSrcTableService.selectByDmStrategyId(dsPO));
		dsPO.setDmTargetTablePOList(dmTargetTableService.selectByDmStrategyId(dsPO));
		return dsPO;
	}

	/**
	 * 保存到草稿箱：保证策略名称不同 1、用户新增策略的中途，保存草稿 2、草稿箱列表，编辑
	 * 
	 * @param record
	 * @return 0：存在相同名称的计划，不可以保存草稿
	 * @throws BaseAppException
	 */
	@RequestMapping("addForDraft")
	@ResponseBody
	public int addForDraft(DmStrategyPO record) throws BaseAppException {
		logger.debug("add record begin...record=[{0}]", record);
		return dmStrategyService.addForDraft(record);
	}

	/**
	 * 添加策略组，主要是为了获取策略组号、策略组名称、计划ID
	 * 
	 * @param dmPlanId
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("addStrategyGroup")
	@ResponseBody
	public DmStrategyPO addStrategyGroup(DmPlanPO dpPO) throws BaseAppException {
		return dmStrategyService.addStrategyGroup(dpPO);
	}

	/**
	 * 拖动策略，改变策略信息：策略与计划的关系
	 * 
	 * @param moveId
	 * @param targetId
	 * @param moveType
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("drag")
	@ResponseBody
	public int drag(@RequestParam(value = "moveId", required = true) Integer moveId,
			@RequestParam(value = "targetId", required = true) Integer targetId,
			@RequestParam(value = "moveType", required = true) String moveType) throws BaseAppException {
		return dmStrategyService.drag(moveId, targetId, moveType);
	}

	/**
	 * 删除策略组，删除这个组下的所有策略
	 * 
	 * @param record
	 * @return
	 * @throws BaseAppException
	 */
	@RequestMapping("deleteGroup")
	@ResponseBody
	public int deleteGroup(DmStrategyPO record) throws BaseAppException {
		logger.debug("delete record begin...record=[{0}]", record);
		DmPlanRelationPO dprPO = new DmPlanRelationPO();
		dprPO.setGroupNbr(record.getDmStrategyId());
		List<DmPlanRelationPO> dprPOList = dmPlanRelationDao.selectByGroupNbr(dprPO);
		for (DmPlanRelationPO po : dprPOList) {
			record.setDmStrategyId(po.getDmStrategyId());
			dmStrategyService.delete(record);
		}
		return 1;
	}

}
